<template>
  <div class="todo-list" :class="{ 'completed-list': category.isCompleted }">
    <div class="list-header" :style="{ backgroundColor: getCategoryColor() }">
      <div class="list-title">{{ category.name }}</div>
      <div class="list-count">
        {{ category.isCompleted ? completedTodosCount : todos.length }}
      </div>
    </div>
    <div class="list-body" :class="{ empty: getIsEmpty() }">
      <!-- 普通分类列表 -->
      <template v-if="!category.isCompleted && todos.length > 0">
        <div class="todo-items-container">
          <TodoItem
            v-for="todo in todos"
            :key="todo.todoItemId || todo.id"
            :todo="todo"
            @toggle="$emit('toggle', $event)"
            @update="handleUpdate"
            @dragstart="handleDragStart($event, todo)"
            @dragover.prevent="handleDragOver"
            @dragenter.prevent
            @drop="handleDrop($event, todo)"
          />
        </div>
      </template>

      <!-- 已完成待办分类列表 - 按标签分组 -->
      <template v-else-if="category.isCompleted">
        <div v-if="groupedCompletedTodos.length === 0" class="empty-message">暂无已完成待办</div>
        <div v-for="group in groupedCompletedTodos" :key="group.id" class="completed-group">
          <!-- 标签分组标题 -->
          <div class="group-header" @click="toggleGroup(group.id)">
            <span class="group-title">{{ group.name }}</span>
            <span class="group-count">{{ group.todos.length }}</span>
            <span class="group-toggle" :class="{ 'is-open': isGroupOpen(group.id) }">▼</span>
          </div>

          <!-- 分组下的待办事项 -->
          <div class="group-items" v-show="isGroupOpen(group.id)">
            <TodoItem
              v-for="todo in group.todos"
              :key="getTodoId(todo)"
              :todo="todo"
              @toggle="$emit('toggle', $event)"
              @update="handleUpdate"
            />
          </div>
        </div>
      </template>

      <div v-else class="empty-message">暂无待办事项</div>
    </div>
  </div>
</template>

<script setup>
import TodoItem from './TodoItem.vue'
import { ref, computed } from 'vue'
import { updateShowSort } from '@/api/todo'

// 已展开的分组ID
const openGroups = ref([])

// 拖拽相关状态
const draggedItem = ref(null)

// 辅助函数：获取待办项的ID（兼容不同的数据结构）
const getTodoId = (todo) => {
  return todo.todoItemId || todo.id
}

const props = defineProps({
  category: {
    type: Object,
    required: true,
  },
  todos: {
    type: Array,
    default: () => [],
  },
  allTodos: {
    type: Array,
    default: () => [], // 所有待办事项，包括已完成的
  },
  allCategories: {
    type: Array,
    default: () => [], // 所有分类
  },
})

const emit = defineEmits(['toggle', 'update', 'reorder'])

// 处理待办事项更新
const handleUpdate = (updatedTodo) => {
  // 直接向上传递更新事件
  emit('update', updatedTodo)
}

// 拖拽开始 - 从子组件接收拖拽开始事件
const handleDragStart = ({ todo }) => {
  draggedItem.value = todo
}

// 拖拽悬停
const handleDragOver = (event) => {
  event.preventDefault()
  event.dataTransfer.dropEffect = 'move'

  // 添加拖拽悬停样式效果
  const todoItem = event.target.closest('.todo-item')
  if (todoItem && !todoItem.classList.contains('dragging')) {
    todoItem.classList.add('drag-over')
  }
}

// 拖拽放置
const handleDrop = async (event, targetTodo) => {
  event.preventDefault()

  // 移除所有拖拽相关样式
  document.querySelectorAll('.todo-item').forEach((item) => {
    item.classList.remove('dragging', 'drag-over')
    item.draggable = false
  })

  // 如果没有拖拽项或目标项与拖拽项相同，则不处理
  if (!draggedItem.value || getTodoId(targetTodo) === getTodoId(draggedItem.value)) {
    return
  }

  // 为了UI立即反馈，先在本地调整顺序
  const updatedTodos = [...props.todos]
  const draggedIndex = updatedTodos.findIndex(
    (item) => getTodoId(item) === getTodoId(draggedItem.value),
  )
  const targetIndex = updatedTodos.findIndex((item) => getTodoId(item) === getTodoId(targetTodo))

  // 从数组中移除拖拽项
  const [movedItem] = updatedTodos.splice(draggedIndex, 1)
  // 将拖拽项插入到目标位置
  updatedTodos.splice(targetIndex, 0, movedItem)

  // 提取所有ID，保持新的顺序
  const orderedIds = updatedTodos.map((todo) => getTodoId(todo))

  // 通知父组件更新顺序 - 立即更新UI
  emit('reorder', {
    labelId: props.category.id,
    todos: updatedTodos,
  })

  try {
    // 调用API保存新的顺序
    const result = await updateShowSort({
      labelId: props.category.id,
      todoItemIds: orderedIds,
    })

    if (!result.success) {
      console.error('待办项排序更新出错:', result.msg)
    }
  } catch (error) {
    console.error('待办项排序更新出错:', error)
  }

  // 清除拖拽状态
  draggedItem.value = null
}

// 计算已完成的待办事项总数
const completedTodosCount = computed(() => {
  return props.allTodos.filter((todo) => todo.completed).length || 0
})

// 按标签分组的已完成待办事项
const groupedCompletedTodos = computed(() => {
  // 获取所有已完成的待办
  const completedTodos = props.allTodos.filter((todo) => todo.completed)

  // 按标签分组
  const groups = {}
  completedTodos.forEach((todo) => {
    if (!groups[todo.labelId]) {
      // 查找标签信息
      const label = props.allCategories.find((cat) => cat.id === todo.labelId)

      if (label) {
        groups[todo.labelId] = {
          id: todo.labelId,
          name: label.name,
          todos: [],
        }
      }
    }

    if (groups[todo.labelId]) {
      groups[todo.labelId].todos.push(todo)
    }
  })

  // 转换为数组
  return Object.values(groups)
})

// 判断是否为空
const getIsEmpty = () => {
  if (props.category.isCompleted) {
    return completedTodosCount.value === 0
  }
  return props.todos.length === 0
}

// 切换分组的展开/折叠状态
const toggleGroup = (groupId) => {
  const index = openGroups.value.indexOf(groupId)
  if (index === -1) {
    openGroups.value.push(groupId)
  } else {
    openGroups.value.splice(index, 1)
  }
}

// 判断分组是否展开
const isGroupOpen = (groupId) => {
  return openGroups.value.includes(groupId)
}

// 获取标签颜色，有颜色则使用，无颜色则使用默认蓝色
const getCategoryColor = () => {
  return props.category.color || '#4361ee'
}
</script>

<style scoped>
.todo-list {
  display: flex;
  flex-direction: column;
  background-color: white;
  border-radius: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  min-height: 400px;
  height: 100%;
  max-height: 100%;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 18px 20px;
  border-bottom: 1px solid #f5f5f7;
  background-color: #4361ee;
  min-width: 0;
}

.list-title {
  font-size: 18px;
  font-weight: 600;
  color: #fff;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
  margin-right: 10px;
}

.list-count {
  background-color: #f5f5f7;
  border-radius: 12px;
  padding: 4px 10px;
  font-size: 14px;
  color: #86868b;
  font-weight: 500;
  flex-shrink: 0;
}

.list-body {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  height: 100%;
  max-height: calc(100% - 60px);
}

.list-body.empty {
  justify-content: center;
  align-items: center;
}

.empty-message {
  color: #86868b;
  font-size: 15px;
  text-align: center;
}

.todo-items-container {
  display: flex;
  flex-direction: column;
  width: 100%;
}

/* 拖拽相关样式 */
.todo-item.dragging {
  opacity: 0.5;
  cursor: grabbing;
}

.todo-item.drag-over {
  border: 2px dashed #4361ee;
  padding: 16px 18px;
  background-color: rgba(67, 97, 238, 0.05);
}

/* 分组样式 */
.completed-group {
  margin-bottom: 15px;
}

.group-header {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
  cursor: pointer;
  margin-bottom: 5px;
  transition: background-color 0.2s;
}

.group-header:hover {
  background-color: #f0f0f0;
}

.group-title {
  flex: 1;
  font-size: 14px;
  color: #1d1d1f;
}

.group-count {
  background-color: #e5e5ea;
  color: #86868b;
  border-radius: 10px;
  padding: 2px 6px;
  font-size: 12px;
  margin-right: 8px;
}

.group-toggle {
  font-size: 10px;
  color: #86868b;
  transition: transform 0.3s;
}

.group-toggle.is-open {
  transform: rotate(180deg);
}

.group-items {
  padding-left: 15px;
  margin-bottom: 10px;
}

/* 优化滚动条样式 */
.list-body::-webkit-scrollbar {
  width: 6px;
}

.list-body::-webkit-scrollbar-track {
  background: transparent;
}

.list-body::-webkit-scrollbar-thumb {
  background-color: #d2d2d7;
  border-radius: 3px;
}

.list-body::-webkit-scrollbar-thumb:hover {
  background-color: #86868b;
}

@media (max-width: 768px) {
  .todo-list {
    min-height: unset;
    height: auto;
    max-height: none;
    box-shadow: none;
    overflow: visible;
    margin-bottom: 20px;
  }

  .list-body {
    padding: 20px 0;
    overflow-y: visible;
    height: auto;
    max-height: none;
    flex: 0 0 auto;
  }
}
</style>
